from .models import Profile

from rest_framework import serializers
from rest_framework.authtoken.models import Token
from django.contrib.auth import authenticate


class ProfileSerializer(serializers.ModelSerializer):

    token = serializers.SerializerMethodField()
    user = serializers.SerializerMethodField()
    class Meta:
        model = Profile
        fields = "__all__"

    def get_token(self, obj):
        user = obj.user
        token, is_create = Token.objects.get_or_create(user=user)

        return token.key

    def get_user(self, obj):
        return obj.user.id

class LoginSerializer(serializers.Serializer):

    username = serializers.CharField(required=True)
    password = serializers.CharField(required=True)

    #参数的校验
    #单独校验
    #
    # def validate_username(self, data):
    #     return data
    #
    # def validate_password(self, data):
    #     return data

    def validate(self, attrs):

        # 校验全部字段
        username = attrs["username"]
        password = attrs["password"]

        user = authenticate(username=username, password=password)

        if not user:
            raise serializers.ValidationError("用户名或密码不正确")
        else:

            Profile.objects.get_or_create(user=user)
            Token.objects.get_or_create(user=user)
            attrs['user'] = user
            return attrs


class ResetPassSerializer(serializers.Serializer):
    new_password = serializers.CharField(required=True, min_length=6)
    confirm_password = serializers.CharField(required=True, min_length=6)

    # 参数的校验
    # 单独校验
    #
    # def validate_username(self, data):
    #     return data
    #
    # def validate_password(self, data):
    #     return data

    def validate(self, attrs):

        # 校验全部字段
        new_password = attrs["new_password"]
        confirm_password = attrs["confirm_password"]

        if new_password != confirm_password:
            raise serializers.ValidationError("密码不一致")
        else:
            return attrs